package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pojo.LeaveMessage;
import com.ruoyi.service.LeaveMessageService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.utils.R;
import com.ruoyi.vo.LeaveMessageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/leave")
public class LeaveMessageController {

    @Autowired
    private LeaveMessageService leaveMessageService;

    @Autowired
    private ISysUserService iSysUserService;

    @GetMapping("/messagelist")
    public R<List<LeaveMessageDto>> messageList(Integer id){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("productid",id);
        List<LeaveMessage> list = leaveMessageService.list(wrapper);
        List<LeaveMessageDto> dtoList = new ArrayList<>();
        for (LeaveMessage i : list) {
            LeaveMessageDto leaveMessageDto = new LeaveMessageDto();
            leaveMessageDto.setUserid(i.getUserid());
            leaveMessageDto.setContent(i.getContent());
            leaveMessageDto.setCreateTime(i.getCreateTime());
            leaveMessageDto.setId(i.getId());
            leaveMessageDto.setProductid(i.getProductid());
            SysUser sysUser = iSysUserService.selectUserById(i.getUserid().longValue());
            leaveMessageDto.setUser(sysUser);
            dtoList.add(leaveMessageDto);
        }
        return R.success(dtoList);
    }

    @PostMapping("/addmessage")
    public R<String> addMessage(@RequestBody LeaveMessage message){
        message.setUserid(Integer.parseInt(String.valueOf(SecurityUtils.getUserId())));
        message.setCreateTime(new Date());
        int i = leaveMessageService.addMessage(message);
        if (i>0){
            return R.success("新增成功！");
        }else {
            return R.error("新增失败！");
        }
    }
}
